/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.swosh.stomp.ejb;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Implementace PersonWS. Obstarává webovou službu geocoding od googlu.
 * @author swosh
 */
@Stateless(name="PersonWS")
@Remote(PersonWSRemote.class)
@Local(PersonWS.class)
@WebService(serviceName = "personServise", targetNamespace = "personNS", portName = "personPort")
public class PersonWSBean implements PersonWS, PersonWSRemote {

    private static final Logger log = Logger.getLogger(PersonDAOBean.class.getSimpleName());

    /**
     * Metoda zjistí souřadnice z adresy osoby.
     * @param p Person
     * @return
     */
    @WebMethod
    @Override
    public Person getLatAndLon(Person p) throws Exception{
        //Spojíme adresu do jednoho stringu
        String address = p.getStreet() + " " + p.getNumOri() + ", " + p.getMunicipalty();
        
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            //Z odeslané URI na geocoding službu dostaneme odpověď ve xml podobě.
            Document d = db.parse(sestavURL(address));
            //A ten xml dokument projdeme
            NodeList places = d.getElementsByTagName("location");
            Node misto = places.item(0);
            NodeList childs = misto.getChildNodes();
            String lon = null;
            String lat = null;
            for (int i = 0; i < childs.getLength(); i++) {
                Node node = childs.item(i);
                if ("lat".equals(node.getNodeName())) {
                    //Získíme latitude
                    lat = node.getTextContent();
                }
                if ("lng".equals(node.getNodeName())) {
                    //a longtitude
                    lon = node.getTextContent();
                }
            }

            if (lat == null || lon == null) {
                throw  new Exception("Getting coordinates failed " + address);               
            } else {
                p.setLat(Double.parseDouble(lat));
                p.setLon(Double.parseDouble(lon));
                return p;
            }
        
    }

    private static String sestavURL(String address) throws UnsupportedEncodingException {
        return "http://maps.google.com/maps/api/geocode/xml?sensor=false&address=" + URLEncoder.encode(address, "UTF-8");


    }
}
